<?php

namespace app\api\controller;

use addons\third\model\Third;
use app\common\controller\Api;
use app\common\controller\ApiResponse;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Config;
use app\common\model\District;
use app\common\model\ShopAudit;
use app\common\model\User as UserModel;
use fast\Random;
use think\Db;
use think\Exception;
use think\Log;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','get_session_key', 'wemini_login', 'register_new', 'direct', 'auth_mobile'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 测试登录
     */
    public function direct(){
        $id = $this->request->param('id');
        if(!$id){
            $this->error("参数错误");
        }
        $this->auth->direct($id);
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success(__('Logged in successful'), $data);
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $email = $this->request->request('email');
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError(),[],60000);
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 微信获取session_key
     */
    public function get_session_key(){
        $code = $this->request->post('code');
        $platform = 'wemini';
        $config = $this->getThirdConfig($platform);
        try {
            $app = new \addons\third\library\Application($config);
            //获取session_key;
            $result = $app->{$platform}->getOpenId($code);
        }catch(Exception $e){
            $this->error($e->getMessage(), '', $e->getCode());
        }

        // 自动登录操作
        $where = [
            'openid' => $result['openid'],
            'platform' => $platform,
        ];
        $Third = new Third();
        $third = $Third->where($where)->find();
        $data['is_bind'] = 0;
        if ($third) {
            if($third['user_id']){
                $user = UserModel::get($third['user_id']);
                if ($user){
                    $this->auth->direct($third['user_id']);
                    $data['is_bind'] = 1;
                    $data['userinfo']  = $this->auth->getUserinfo();
                }
            }
        }
        $this->success(__('获取成功'), $data);
    }

    /**
     * 微信登录
     */
    public function wemini_login()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $rawData = $this->request->request('rawData');
        $signature = $this->request->request('signature');
        $encryptedData = $this->request->request('encryptedData');
        $iv = $this->request->request('iv');
        $platform = 'wemini';
        $config = $this->getThirdConfig($platform);

        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        try {
            $result = $app->{$platform}->getUserInfo(['code'=>'', 'rawData'=>$rawData, 'signature'=>$signature, 'encryptedData'=>$encryptedData, 'iv'=>$iv]);
            //Log::record("########### getUserInfo");
            //Log::record($result);
        } catch (Exception $e) {
            $this->error($e->getMessage(), '', $e->getCode());
        }
        if (!$result) $this->error(__('Operation failed'), $url);

//        $openid = $result['openid'];
        $loginret = \addons\third\library\Service::login_connect($platform, $result);
        if (!$loginret) $this->success('未注册账号', ['is_bind' => false]);

        $data = [
            'is_bind'   => true,
            'userinfo'  => $this->auth->getUserinfo(),
            'thirdinfo' => $result,
//            'openid'    => $openid,
        ];
        $this->success(__('Logged in successful'), $data);
    }

    /**
     * 通过微信注册
     */
    public function register_new(){
        $user_type = $this->request->param('user_type', UserModel::USER_TYPE_NORMAL);
        $store_id = $this->request->param('store_id', 0);
        $province_id = $this->request->param('province_id', 27833);
        $city_id = $this->request->param('city_id', 28141);
        $area_id = $this->request->param('area_id', 0);
        $industry = $this->request->param('industry', '');
        $mobile = $this->request->param('mobile', '');
        if(!in_array($user_type, [UserModel::USER_TYPE_NORMAL, UserModel::USER_TYPE_VIP])){
            $this->error("参数错误");
        }
        if($user_type == UserModel::USER_TYPE_VIP){
            if(empty($province_id) || empty($city_id) || empty($area_id)){
                $this->error("请选择所在区域");
            }
            if(empty($store_id)){
                $this->error("请选择所属分会");
            }
        }
        if(empty($industry)){
            $this->error("请填写行业");
        }
        if(empty($mobile)){
            $this->error("请填写手机号码");
        }
        if(!preg_match("/^1[3-9]{1}\d{9}$/",$mobile)){
            $this->error("手机号码格式不正确");
        }
        $wemini_user_info = session('wemini_user_info');

        if(empty($wemini_user_info)){
            $this->error("请先授权获取微信信息");
        }

        $count_user = model('User')->max('id');
        $username = "u". ($count_user + 1);
        $password = "123456";
        $email = '';

        $extend['user_type'] = $user_type;
        $extend['store_id'] = $store_id;
        $extend['province_id'] = $province_id;
        $extend['city_id'] = $city_id;
        $extend['area_id'] = $area_id;
        $extend['industry'] = $industry;
        $extend['openid'] = $wemini_user_info['openid'];
        $extend['unionid'] = $wemini_user_info['unionid'];
        if(!Third::where('openid', $extend['openid'])->count()){
            $this->error("授权获取微信信息失败");
        }

        $avatar = $wemini_user_info['avatarUrl'];
        // 处理微信头像
        if (isset($wemini_user_info['avatarUrl'])) {
            $avatar = htmlspecialchars(strip_tags($wemini_user_info['avatarUrl']));
            // 处理头像  下载到服务器
            $siteRoot = getcwd();
            $uploadDir = '/uploads/user/avatar/' . date('Ymd') . '/';
            $rootUploadDir = $siteRoot . $uploadDir;
            if (!file_exists($rootUploadDir)) {
                if (!mkdir($rootUploadDir, 0777, true)) {
//                return false;
//                throw new Exception('目录创建失败，没有权限');
                    Log::record('目录创建失败，没有权限，头像 ');
                }
            }

            if (!empty($avatar)) {
                $ext = pathinfo($avatar, PATHINFO_EXTENSION);
                $ext = $ext ? $ext : 'jpg';
                $avatarName = md5($wemini_user_info['openid']) . '.' . $ext;
                $avatarFromtData = file_get_contents($avatar);
                if (!$avatarFromtData) {
//                return false;
//                throw new Exception('文件错误！');
                    Log::record('文件错误！头像');
                }

                if (!file_put_contents($rootUploadDir . $avatarName, $avatarFromtData)) {
//                return false;
//                throw new Exception('文件保存失败！');
                    Log::record('文件保存失败！头像');
                }else{
                    $avatar = $uploadDir . $avatarName;
                }
            }
        }
        $extend['nickname'] = $wemini_user_info['nickName'];
        $extend['avatar'] = $avatar;
        $extend['gender'] = $wemini_user_info['gender'];
        $ret = $this->auth->register(md5($username), $password, $email, $mobile, $extend);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取用户信息
     */
    public function get_user_info(){
        $user_id = $this->auth->id;
        $data = model('User')->where('id', $user_id)->field('id,avatar,store_id,nickname,user_type,province_id,city_id,area_id,industry,is_follow_public_wechat,number,mobile')->find();
        $data['avatar'] = getRealImg($data['avatar']);
        $data['store_name'] = model('Store')->where('id', $data['store_id'])->value('name') ?: '';
        $data['province_name'] = District::where('id', $data['province_id'])->value('name') ?: '';
        $data['city_name'] = District::where('id', $data['city_id'])->value('name') ?: '';
        $data['area_name'] = District::where('id', $data['area_id'])->value('name') ?: '';
        $data['service_mobile'] = Config::getConfigValue('service_mobile') ?: '';
        unset($data['province_id']);
        unset($data['city_id']);
//        unset($data['area_id']);
        $data['is_audit'] = 0;
        $audit = ShopAudit::where(['user_id'=> $user_id])->order('id desc')->find();
        if($audit){
            $data['is_audit'] = $audit['status'];
            if($audit['status'] == ShopAudit::STATUS_AUDIT_PASS && $audit['expiration_time'] <= time()){
                $data['is_audit'] = ShopAudit::STATUS_AUDIT_EXPIRATION;
            }
        }
        $this->success("获取成功", $data);
    }

    /**
     * 修改用户资料
     */
    public function save_user_info(){
        $user_type = $this->request->param('user_type', UserModel::USER_TYPE_NORMAL);
        $store_id = $this->request->param('store_id', 0);
        $province_id = $this->request->param('province_id', 27833);
        $city_id = $this->request->param('city_id', 28141);
        $area_id = $this->request->param('area_id', 0);
        $industry = $this->request->param('industry', '');
        $nickname = $this->request->param('nickname', '');
        if(!in_array($user_type, [UserModel::USER_TYPE_NORMAL, UserModel::USER_TYPE_VIP])){
            $this->error("参数错误");
        }
        if(empty($nickname)){
            $this->error("请填写昵称");
        }
        if($user_type == UserModel::USER_TYPE_VIP){
            if(empty($province_id) || empty($city_id) || empty($area_id)){
                $this->error("请选择所在区域");
            }
            if(empty($store_id)){
                $this->error("请选择所属分会");
            }
        }
        if(empty($industry)){
            $this->error("请填写行业");
        }

        $user = $this->auth->getUser();
        $params = $this->request->param();
        $res = $user->save($params);
        if($res){
            $this->success("修改成功");
        }
        $this->error("修改失败");
    }

    /**
     * 修改用户昵称
     */
    public function save_nickname(){
        $nickname = $this->request->param('nickname', '');
        if(empty($nickname)){
            $this->error("请填写昵称");
        }

        $user = $this->auth->getUser();
        $params = $this->request->param();
        $res = $user->save($params);
//        if($res){
            $this->success("修改成功");
//        }
//        $this->error("修改失败");
    }

    /**
     * 获取微信手机号码
     * @return void
     */
    public function auth_mobile()
    {
        $params = [
//            'code' => $this->request->post('code'),
            'encryptedData' => $this->request->post('encryptedData'),
//            'encryptedData' => urldecode($this->request->param('encryptedData')),
//            'iv' => urldecode($this->request->param('iv')),
            'iv' => $this->request->post('iv'),
        ];
        $platform = 'wemini';
        $config = $this->getThirdConfig($platform);

        // 开启事务
        Db::startTrans();
        try {
            $app = new \addons\third\library\Application($config);
            //解密手机号码
            $result = $app->{$platform}->decryptorMobile($params);
            if($result){
                if (isset($result->purePhoneNumber) || !empty($result->purePhoneNumber)) {
                    $data = $result->purePhoneNumber;
                } else {
                    throw new Exception('手机号码获取失败', ApiResponse::CODE_WECHAT_OTHER);
                }
            } else {
                throw new Exception('手机号码获取失败', ApiResponse::CODE_WECHAT_OTHER);
            }
            // 提交事务
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            $code = 0;
            if ($e->getCode() == 1) {
                $code = ApiResponse::CODE_WECHAT_ACCESSTOKEN_ERROR;
            } else if ($e->getCode() == 2) {
                $code = ApiResponse::CODE_WECHAT_CODE_EMPTY;
            } else if ($e->getCode() == 3) {
                $code = ApiResponse::CODE_WECHAT_OTHER;
            }
            $this->error($e->getMessage(), $e->getMessage(), $code);
        }

        $this->success(__('获取成功'), $result);
    }
    /**
     * 获取微信手机号码 并绑定
     * @return void
     */
    public function auth_mobile_to_bind()
    {
        $params = [
//            'code' => $this->request->post('code'),
            'encryptedData' => $this->request->post('encryptedData'),
//            'encryptedData' => urldecode($this->request->param('encryptedData')),
//            'iv' => urldecode($this->request->param('iv')),
            'iv' => $this->request->post('iv'),
        ];
        $platform = 'wemini';
        $config = $this->getThirdConfig($platform);

        // 开启事务
        Db::startTrans();
        try {
            $app = new \addons\third\library\Application($config);
            //解密手机号码
            $result = $app->{$platform}->decryptorMobile($params);
            if($result){
                if (isset($result->purePhoneNumber) || !empty($result->purePhoneNumber)) {
                    $userinfo = UserModel::getByMobile($result->purePhoneNumber);
                    if($userinfo){
                        $this->error(__('手机号码已被占用'));
                    }

                    $userData = $this->auth->getUser();
                    if (!empty($userData['mobile'])) {
                        $this->error(__('Current user alreay bind mobile'));
                    }

                    $userData->save([
                        'mobile' => $result->purePhoneNumber
                    ]);
                } else {
                    throw new Exception('手机号码获取失败', ApiResponse::CODE_WECHAT_OTHER);
                }
            } else {
                throw new Exception('手机号码获取失败', ApiResponse::CODE_WECHAT_OTHER);
            }
            // 提交事务
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            $code = 0;
            if ($e->getCode() == 1) {
                $code = ApiResponse::CODE_WECHAT_ACCESSTOKEN_ERROR;
            } else if ($e->getCode() == 2) {
                $code = ApiResponse::CODE_WECHAT_CODE_EMPTY;
            } else if ($e->getCode() == 3) {
                $code = ApiResponse::CODE_WECHAT_OTHER;
            }
            $this->error($e->getMessage(), $e->getMessage(), $code);
        }

        $this->success(__('绑定成功'), $result);
    }

    /**
     * 解绑手机号码
     */
    public function debindMobile(){
        $user = $this->auth->getUser();
        $user->mobile = '';
        $res = $user->save();
        if($res === false)
        {
            $this->error('解除绑定失败');
        }
        $this->success(__('Debind account success'));
    }
    /**
     * 获取第三方登录插件配
     */
    protected function getThirdConfig($platform, $scope = 'snsapi_base')
    {
        $config = get_addon_config('third');
        if ($platform == Third::PLATFORM_WECHAT) {
            $config[Third::PLATFORM_WECHAT] = [
                'app_id'        => Config::getConfigValue('wechat_appid'),
                'app_secret'    => Config::getConfigValue('wechat_secret'),
                'secret'    => Config::getConfigValue('wechat_open_secret'),
                'scope'         => $scope
            ];
        } else if ($platform == Third::PLATFORM_WEMINI) {
            $config[Third::PLATFORM_WEMINI] = [
                'app_id'        => Config::getConfigValue('miniapp_wechat_appid'),
                'app_secret'    => Config::getConfigValue('miniapp_wechat_secret'),
            ];
        } else {
            $this->error('第三方登录方式不存在！');
        }
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }

        return $config;
    }
}
